let app = getApp();
const api = require("../../server/Api.js");
const cartHelper = require("../../server/CartHelper.js")
const _user = require("../../utils/User.js");
const util = require("../../utils/util.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsId: "",
    // 商品详情展示数据
    detaiData: {},
    modes: {}, //规格
    statusBar: app.globalData.StatusBar,
    curSelectAddress: "", //当前选择的地址
    selfSelAddress: '', //从选择器选择的地址
    showModelDialog: false, //是否显示规格弹窗
    selectMode: "默认", //当前选中规格
    buyCount: 1, //购买商品数量（临时）
    carts: 0, //购物车商品数量
    isFavorite: false, //是否关注
    buyType: 0, //购买方式:0加入购物车;1:立即购买
    //商品信息
    goodsInfo: [],
    addresses: [], //收货地址
    isSellOut: false, //售磐
    isTimeOut: false, //结束
    showShareDialog: false,
    actTime: '2029-10-02 00:00:00', //活动时间
    countDownData: [],
    buyList: [],
    shopInfo: null,
    imagePath: "",
    isInterval: true,
    todayStr: app.getZtDate().replace("/", "-"),
    options: {}
  },


  onLoad: function(options) {
    this.setData({
      options: options
    })
    let that = this;
    if (!app.globalData.loginDone) {
      app.wxLogin().then(res => {
        let userBean = res;
        if (userBean) {
          app.globalData.userBean = res;
          _user.saveUser(userBean);
        }
        app.globalData.loginDone = true
        that.loadFunc(that, that.data.options)
      }).catch(msg => {
        app.globalData.userBean = null;
        _user.saveUser(null);
        app.globalData.loginDone = true
        that.loadFunc(that, that.data.options)
      });
    } else {
      that.loadFunc(that, that.data.options)
    }
  },
  loadFunc(that, options) {
    let id = options.id;
    that.setData({
      goodsId: id
    })
    if (options.uid) {
      app.globalData.shareUserId = options.uid
    }
    that.queryGoodsDetail();
  },
  //小于10的格式化函数
  timeFormat(param) {
    return param < 10 ? '0' + param : param;
  },
  //倒计时函数
  countDown() {
    // 获取当前时间
    let newTime = new Date().getTime();
    //获取活动时间
    let actTime = this.data.actTime;
    let countDownObj = [];
    // 获取活动结束时间的总毫秒数
    let endTime = util.stringToDate(actTime).getTime();
    let obj = null;
    // 如果活动未结束，对时间进行处理
    if (endTime - newTime > 0) {
      //获得距离结束时间的总秒数
      let time = (endTime - newTime) / 1000;
      // 获取天、时、分、秒
      let day = parseInt(time / (60 * 60 * 24));
      let hou = parseInt(time % (60 * 60 * 24) / 3600);
      let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
      let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
      obj = {
        day: this.timeFormat(day),
        hou: this.timeFormat(hou),
        min: this.timeFormat(min),
        sec: this.timeFormat(sec)
      }
      if (this.data.isInterval) {
        setTimeout(this.countDown, 1000);
      }
    } else { //活动已结束，全部设置为'00'
      this.setData({
        isTimeOut: true
      })
      obj = {
        day: '00',
        hou: '00',
        min: '00',
        sec: '00'
      }
    }
    countDownObj.push(obj);
    // 渲染，然后每隔一秒执行一次倒计时函数
    this.setData({
      countDownData: countDownObj
    })
  },
  onShow: function() {

  },

  getShopInfo: function(callback) {
    const that = this;
    if (!that.data.shopInfo) {
      api.getShopInfo(app.globalData.shopId).then(res => {
        console.log("店铺信息:", res);
        //请求成功
        that.setData({
          shopInfo: res
        })
        if (callback) {
          callback();
        }
      }).catch(msg => {
        let message = typeof msg == "string" ? msg : msg.message;
        app.showToast(message);
      })
    } else {
      if (callback) {
        callback();
      }
    }
  },
  getBuyList() {
    let that = this;
    let param = {
      pageNumber: 1,
      pageSize: 14,
      spuId: this.data.detaiData.spuId
    }
    api.orderBuyList(param).then(res => {
      console.log("购买记录", res)
      that.setData({
        buyTotal: res.total,
        buyList: res.records
      })
    }).catch(msg => {
      var message = typeof msg == "string" ? msg : msg.message;
      app.showToast(message);
    })
  },

  //分页查询地址
  queryAddress: function() {
    let that = this;
    let userBean = app.globalData.userBean;

    let prams = {
      pageSize: 20,
      pageIndex: 1,
      userId: userBean.consumerId
    };
    api.queryMyAddress(prams).then(res => {
      //请求成功
      that.setData({
        addresses: res.records,
      })
    }).catch(msg => {
      var message = typeof msg == "string" ? msg : msg.message;
      app.showToast(message);
    })
  },


  // 查询购物车数量
  queryCartCount: function() {
    let that = this;
    let userInfo = app.globalData.userBean;
    if (!userInfo || !userInfo.consumerId) {
      return;
    }
    let prams = {
      pageSize: 100,
      pageNumber: 1,
      storeId: app.globalData.shopId,
      platformId: app.globalData.platformId,
      userId: userInfo.consumerId
    };
    api.queryCartList(prams).then(res => {
      //请求成功
      let count = 0;
      console.log(res.records);
      if (res.records.length > 0 && res.records[0].cartVO.length > 0) {
        for (let i = 0; i < res.records[0].cartVO.length; i++) {
          count += parseInt(res.records[0].cartVO[i].goodsQuantity);
        }
      }
      that.setData({
        carts: count
      })
    }).catch(msg => {
      var message = typeof msg == "string" ? msg : msg.message;
      app.showToast(message);
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    let that = this
    let userId = "";
    let userInfo = app.globalData.userBean;
    if (userInfo && userInfo.consumerId) {
      userId = userInfo.consumerId
    }
    let imageUrl = that.data.detaiData.images[0].url;
    if (that.data.imagePath && that.data.imagePath !== "") {
      imageUrl = that.data.imagePath
    }
    return {
      title: that.data.shopInfo.storeName + "-" + that.data.detaiData.title,
      path: 'pages/goods-detail/goods-detail?id=' + that.data.detaiData.spuId + "&uid=" + userId,
      imageUrl: imageUrl,
      success: function(res) {
        tt.showToast('转发成功');
      },
      fail: function() {
        tt.showToast('转发失败');
      }
    }
  },

  // 加入购物车
  onAddCount: function() {
    let userBean = app.globalData.userBean;
    if (!userBean || !userBean.consumerId) {
      tt.navigateTo({
        url: '../login/login',
      })
    }

    let that = this;
    //服务器加入购物车
    let goodsCount = this.data.buyCount;
    let skuId = this.data.detaiData.skuId;
    let userId = app.globalData.userBean.consumerId;
    api.addCart(this.data.buyCount, skuId, userId).then(res => {
      that.queryCartCount(); //本地加入购物车
      that.dismissDialog();
      tt.showToast({
        title: '加入成功',
      })
    }).catch(msg => {
      let errorMsg = typeof msg == "string" ? msg : msg.message
      tt.showModal({
        title: '提示',
        content: '程序发生了一个意外：' + errorMsg,
      })
    })
  },
  toIndex() {
    tt.switchTab({
      url: '../index/index'
    })
  },
  //前往购物车
  toCart: function(e) {
    let userInfo = app.globalData.userBean;
    if (!(userInfo && userInfo.consumerId)) {
      tt.navigateTo({
        url: '../login/login',
      })
      return
    }
    tt.switchTab({
      url: '../main-cart-new/main-cart'
    })
  },
  goShare() {
    let that = this;
    that.setData({
      showShareDialog: true
    })
  },
  hiddenShareDialog() {
    let that = this;
    that.setData({
      showShareDialog: false
    })
  },
  //查询商品详情
  queryGoodsDetail: function() {
    let that = this;
    let userInfo = app.globalData.userBean;
    let userId = undefined
    if (userInfo && userInfo.consumerId) {
      userId = userInfo.consumerId
    }
    // wx.showNavigationBarLoading()
    api.queryGoodsDetail(this.data.goodsId, userId).then(res => {
      // tt.hideNavigationBarLoading()
      let modes = JSON.parse(res.spec);
      let goodsModes = [modes.spec1.spec_name];
      res.goodsQuantity = 1;
      for (let j = 0; j < res.images.length; j++) {
        res.images[j].url = app.resetImageUrlByPx(res.images[j].url, app.globalData.windowWidth);
      }
      for (let j = 0; j < res.description.length; j++) {
        if (res.description[j].url) {
          res.description[j].url = res.description[j].url.trim();
          res.description[j].url = app.resetImageUrlByPx(res.description[j].url, app.globalData.windowWidth);
        }
      }
      res.dateStr = app.getZtDate(res.deliveryTime);
      res.dateStr1 = app.getZtDate(res.deliveryTime).replace("/", "-");
      that.setData({
        detaiData: res,
        selectMode: modes.spec1.spec_name,
        isSellOut: (res.quantity <= res.sales)
      })

      if (res.storeId && res.storeId != "") {
        app.globalData.shopId = res.storeId
      }
      that.getShopInfo();
      that.queryCartCount();
      that.getBuyList();
      that.countDown();
      //that.createGoodsShareImg();
    }).catch(msg => {
      // tt.hideNavigationBarLoading()
      tt.navigateBack();
      app.showToast("获取商品详情失败!")
      console.log(msg)
    })
  },
  //显示规格
  showMode: function(e) {
    if (this.data.detaiData.receiptInterval != 1 && e.currentTarget.dataset.type === "0") {
      //app.showToast("不是隔天可提货的商品暂不支持加入购物车,请直接购买")
      app.showToast("该商品不支持加上购物车")
      return;
    }
    let userInfo = app.globalData.userBean;
    if (!(userInfo && userInfo.consumerId)) {
      tt.navigateTo({
        url: '../login/login',
      })
      return
    }
    this.setData({
      buyType: e.currentTarget.dataset.type
    });
    this.setData({
      showModelDialog: true,
    })
  },

  //关闭规格
  onCloseMode: function(e) {
    this.setData({
      showModelDialog: false,
    })
  },

  //规格选择
  onModeTypeIndex: function(e) {
    this.setData({
      selectMode: e.currentTarget.id
    })
  },
  //取消底部弹窗
  dismissDialog: function(e) {
    this.setData({
      showModelDialog: false //是否显示规格弹窗
    })
  },
  //修改商品数量
  modifyCount: function(e) {
    let type = e.currentTarget.id;
    let buyCount = this.data.buyCount;
    if (type == "add") {
      if (buyCount > 99) return;
      this.setData({
        buyCount: buyCount + 1
      })
    } else {
      if (buyCount <= 1) return;
      this.setData({
        buyCount: buyCount - 1
      })
    }
  },
  gobuylist() {
    tt.navigateTo({
      url: '../buy-record/buy-record?id=' + this.data.detaiData.spuId
    })
  },
  onUnload() {
    this.setData({
      isInterval: false
    })
  },
  back: function() {
    tt.navigateBack();
  },
  refreshCart: function() {
    this.dismissDialog();
    this.queryCartCount()
  },
  //绘制商品详情转发图片
  createGoodsShareImg() {
    var that = this;
    let drawCount = 1;
    let drawAll = 7;
    that.setData({
      imagePath: ""
    });
    var context = tt.createCanvasContext('mycanvas1', that);
    context.save();
    that.roundRect(context, 0, 0, 210, 168, 10);
    context.setFillStyle('white')
    context.fillRect(0, 0, 210, 168)
    const grd = context.createLinearGradient(0, 0, 210, 0)
    grd.addColorStop(0, '#E94B41')
    grd.addColorStop(1, '#EA4569')
    context.setFillStyle(grd)
    context.fillRect(0, 0, 210, 168)
    context.restore();
    context.draw(true, () => {
      that.saveTempImage(drawCount++, drawAll);
    });
    context.save();
    that.roundRect(context, 4, 4, 202, 142, 10);
    context.setFillStyle('white')
    context.fillRect(4, 4, 202, 142)
    context.restore();
    context.draw(true, () => {
      that.saveTempImage(drawCount++, drawAll);
    });
    tt.downloadFile({
      url: "https://obs.cn-north-1.myhuaweicloud.com/obs-7d37/hh_shequ/190725/20190724001z0.jpg?x-image-process=image/resize,m_pad,w_344,h_196",
      success(res) {
        context.save();
        that.roundRect(context, 19, 12, 172, 98, 10);
        context.setFillStyle('white')
        context.fillRect(19, 12, 172, 98)
        context.drawImage(res.tempFilePath, 19, 12, 172, 98);
        context.restore();
        context.draw(true, () => {
          that.saveTempImage(drawCount++, drawAll);
        });
      }
    })
    context.save();
    context.setFontSize(12);
    context.font = 'normal bold 12px PingFangSC-Semibold';
    context.setFillStyle('#E93324');
    context.fillText("￥", 19, 132);
    context.font = 'normal bold 18px PingFangSC-Semibold';
    context.setFontSize(18);
    context.fillText(that.data.detaiData.minPrice, 29, 132);
    let priceWidth = 12 * (that.data.detaiData.minPrice + "").length - 6
    context.restore();
    context.draw(true, () => {
      that.saveTempImage(drawCount++, drawAll);
    });
    context.save();
    context.font = 'normal normal 12px PingFangSC-Regular';
    context.setFillStyle('#999');
    context.setFontSize(12);
    context.fillText("￥", 19 + priceWidth + 10, 132);
    context.fillText(that.data.detaiData.maxPrice, 19 + priceWidth + 16, 132);
    let priceWidth1 = 6 * (that.data.detaiData.maxPrice + "").length
    context.moveTo(19 + priceWidth + 12, 128)
    context.lineTo(19 + priceWidth + 17 + priceWidth1, 128)
    context.setStrokeStyle('#999')
    context.stroke();
    context.restore();
    context.save();
    context.draw(true, () => {
      that.saveTempImage(drawCount++, drawAll);
    });
    context.save();
    that.roundRect(context, 131, 116, 60, 22, 12);
    context.setFillStyle('white')
    context.fillRect(131, 116, 60, 22)
    const grd1 = context.createLinearGradient(0, 0, 60, 0)
    grd1.addColorStop(0, '#E94B41')
    grd1.addColorStop(1, '#EA4569')
    context.setFillStyle(grd1)
    context.fillRect(131, 116, 60, 22)
    context.restore();
    context.font = 'normal 500 10px PingFangSC-Medium';
    context.setFontSize(10);
    context.setFillStyle('#fff');
    context.fillText("立即抢购", 141, 130);
    context.draw(true, () => {
      that.saveTempImage(drawCount++, drawAll);
    });
    tt.downloadFile({
      url: "https://obs.cn-north-1.myhuaweicloud.com/obs-7d37/hh_shequ/goodlife.png",
      success(res) {
        context.save();
        context.drawImage(res.tempFilePath, 65, 151, 80, 12);
        context.draw(true, () => {
          that.saveTempImage(drawCount++, drawAll);
        });
      }
    })
  },
  saveTempImage(drawCount, drawAll, forceDraw) {
    console.log("saveTempImage", drawCount, drawAll, forceDraw);
    let that = this;
    if (drawCount == drawAll || forceDraw) {
      setTimeout(() => {
        tt.canvasToTempFilePath({
          canvasId: 'mycanvas1',
          success: function(res) {
            var tempFilePath = res.tempFilePath;
            that.setData({
              imagePath: tempFilePath
            });
          },
          fail: function(res) {
            console.log("生成转发图片失败", res);
            tt.showToast({
              title: '生成转发图片失败',
              icon: "none"
            })
            that.setData({
              imagePath: ""
            });
          }
        }, that);
      }, 600)
    }
  },
  //圆角
  roundRect(ctx, x, y, w, h, r) {
    ctx.beginPath()
    ctx.setStrokeStyle('transparent')
    ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
    ctx.moveTo(x + r, y)
    ctx.lineTo(x + w - r, y)
    ctx.lineTo(x + w, y + r)
    ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
    ctx.lineTo(x + w, y + h - r)
    ctx.lineTo(x + w - r, y + h)
    ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)
    ctx.lineTo(x + r, y + h)
    ctx.lineTo(x, y + h - r)
    ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)
    ctx.lineTo(x, y + r)
    ctx.lineTo(x + r, y)
    ctx.stroke()
    ctx.closePath()
    ctx.clip()
  }
})